﻿using Helpers;
using SmallJob.Model;
using SmallJob.Services.Code;
using SmallJob.Services.Implements;
using SmallJob.Services.Interfaces;
using SmallShop.Services.Code;
using SmallShop.Services.Implements;
using SmallShop.Services.Interfaces;
using System;
using System.Linq;
using System.Web.Mvc;

namespace FrontEnd.Controllers
{
    public class PaymentController : Controller
    {
        private readonly ITransactionService _TransactionService;
        private readonly IUserService _UserService;
        private readonly IProvideService _ProvideService;
        private readonly IRequestService _RequestService;
        private readonly IBidRequestService _BidRequestService;
        private readonly ISmsLogService _SmsLogService;
        private readonly IEmailFormatService _EmailFormatService;
        private readonly IOrderService _OrderService;
        private readonly IMMessageService _MMessageService;
        private readonly IMConversationService _MConversationService;
        public PaymentController(IMConversationService MConversationService, IMMessageService MMessageService, IOrderService OrderService, IRequestService RequestService, IProvideService ProvideService, IUserService UserService, ITransactionService TransactionService, IBidRequestService BidRequestService, ISmsLogService SmsLogService, IEmailFormatService EmailFormatService)
        {
            _BidRequestService = BidRequestService;
            _TransactionService = TransactionService;
            _UserService = UserService;
            _RequestService = RequestService;
            _ProvideService = ProvideService;
            _SmsLogService = SmsLogService;
            _EmailFormatService = EmailFormatService;
            _OrderService = OrderService;
            _MConversationService = MConversationService;
            _MMessageService = MMessageService;
        }

        public ActionResult Premium()
        {
            if (TempData["issuccess"] != null)
            {
                ViewData["issuccess"] = TempData["issuccess"];
                ViewData["result"] = TempData["result"];
            }
            return View();
        }

        [HttpPost]
        public ActionResult ModalPremium()
        {
            if (!User.Identity.IsAuthenticated) return Json(false);
            var user = UtilityService.GetLoginUser(_UserService, User);
            if (string.IsNullOrWhiteSpace(user.Phone)) ViewData["needphone"] = true;
            //if (string.IsNullOrWhiteSpace(user.PremiumCode))
            //{
            //    user.PremiumCode = UserUtility.GetRandomString(16);
            //    _UserService.Update(user);
            //}
            ViewData["user"] = user;
            return PartialView();
        }

        [HttpPost]
        public ActionResult CheckoutPremium(int amount, string phone)
        {
            if (!User.Identity.IsAuthenticated) return Json(false);
            var user = UtilityService.GetLoginUser(_UserService, User);
            if (!string.IsNullOrWhiteSpace(phone))
            {
                user.Phone = phone;
                _UserService.Update(user);
            }
            var transaction = new Transaction()
            {
                Amount = amount,
                CreatedDate = DateTime.Now,
                ModifiedDate = DateTime.Now,
                PayerID = user.ID,
                ReceiverID = (int)EUserID.SystemUser,
                Status = (int)ETransactionStatus.Wait_Payment,
                TransactionCode = UserUtility.GetRandomString(16),
                TransactionType = (int)ETransactionType.Payment_Premium
            };
            _TransactionService.Add(transaction);
            string urlcheckout = "";
            SohaPayment pay = new SohaPayment();
            urlcheckout = pay.BuildCheckoutUrl(RootUrl() + "/Payment/ResultPayment", "Nâng cấp premium trên viecnho.com", transaction.ID.ToString(), Convert.ToInt64(amount), UserUtility.GetVerifiedEmail(user), user.Phone ?? "", user.Location ?? "");
            return Redirect(urlcheckout);
        }

        public ActionResult ResultPayment()
        {
            //var premiumcode = Request["order_code"];
            var transactionid = Convert.ToInt32(Request["order_code"]);
            var transaction = _TransactionService.GetById(transactionid);
            var price = Convert.ToInt32(Request["price"]);
            var days = PremiumCalculate.ParseToList(Resources.Resource.PremiumString).Where(i => i.Value == price).FirstOrDefault().Key;
            var convertday = new ConvertDay(days);
            var userid = transaction.PayerID;
            var user = _UserService.GetById(userid);
            if (user == null)
            {
                var error = "Không tìm thấy tài khoản.";
                TempData["result"] = error;
                TempData["issuccess"] = false;
                SendEmailFailedPayment(true, user, price.ToString(), error, "", "");
                return RedirectToAction("Premium");
            }
            if (transaction == null)
            {
                var error = "Không tìm thấy giao dịch.";
                TempData["result"] = error;
                TempData["issuccess"] = false;
                SendEmailFailedPayment(true, user, price.ToString(), error, "", "");
                return RedirectToAction("Premium");
            }
            string error_text = !string.IsNullOrEmpty(Request["error_text"]) ? Request["error_text"] : "";
            SohaPayment pay = new SohaPayment();
            bool check = pay.VerifyReturnUrl();
            string html = "";
            if (check && error_text == "")
            {
                if (transaction.Status == (int)ETransactionStatus.Wait_Payment)
                {
                    transaction.Status = (int)ETransactionStatus.Payment_Done;
                    transaction.ModifiedDate = DateTime.Now;
                    _TransactionService.Update(transaction);
                    var countmonth = (Convert.ToInt32(price) / 100000);
                    TimeSpan time = new TimeSpan(days, 0, 0, 0);
                    if (user.PremiumTo == null)
                    {
                        user.PremiumTo = DateTime.Now;
                    }
                    user.PremiumTo = ((DateTime)user.PremiumTo).AddDays(convertday.Day);
                    user.PremiumTo = ((DateTime)user.PremiumTo).AddMonths(convertday.Month);
                    user.PremiumTo = ((DateTime)user.PremiumTo).AddYears(convertday.Year);
                    user.Premium = true;
                    _UserService.Update(user);

                    //send notify
                    //try catch to enable and disable send email depend on resource
                    try
                    {
                        var format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailPremiumSuccess));
                        var email = UserUtility.GetVerifiedEmail(user);
                        DictionaryTransactionPremiumSuccess dic = new DictionaryTransactionPremiumSuccess(email, user.ProperName, price.ToString(), ((DateTime)user.PremiumTo).ToString("dd/MM/yyyy HH:mm"));
                        UserUtility.NotifyEmail(format, dic);
                    }
                    catch (Exception) { }

                    if (user != null && user.Phone != null)
                    {
                        SmsHelpers smsHelper = new SmsHelpers();
                        string messid = "sms_" + user.ID + "_" + "SohapayPremiumSms";
                        string smsresult = "";
                        string smsContent = "";
                        var cul = System.Globalization.CultureInfo.GetCultureInfo("vi-VN");
                        smsContent = Resources.Resource.SohaPayPremium.Replace("{date}", ((DateTime)user.PremiumTo).ToString("dd-MM-yyyy HH:mm", cul));
                        var smsResultObj = smsHelper.Send(messid, user.Phone, smsContent, out smsresult);
                        _SmsLogService.Add(new SmsLog()
                        {
                            DateCreated = DateTime.Now,
                            MessageID = smsResultObj.message_id,
                            SmsResult = smsresult,
                            Status = smsResultObj.status,
                            UserID = user.ID,
                            SmsContent = smsContent
                        });
                    }
                }
                html += "Cám ơn quý khách, quá trình thanh toán đã được hoàn tất. Tài khoản của bạn là premium đến ngày " + ((DateTime)user.PremiumTo).ToString("dd/MM/yyyy HH:mm");
                TempData["issuccess"] = true;
            }
            else if (check)
            {
                html += "Quá trình thanh toán không thành công do lỗi: " + error_text;
                TempData["issuccess"] = false;
            }
            else
            {
                html += "Thông tin bảo mật không đúng";
                TempData["issuccess"] = false;
            }
            TempData["result"] = html;
            if (!Convert.ToBoolean(ViewData["issuccess"]))
            {
                SendEmailFailedPayment(true, user, price.ToString(), html, "", "");
            }
            return RedirectToAction("Premium");
        }

        public string RootUrl()
        {
            string url = "";
            if (System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"] == "80")
                url = "http://" + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
            else
                url = "http://" + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + ":" + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
            if (Request.ApplicationPath != "/")
                url += Request.ApplicationPath;
            return url;
        }

        [HttpPost]
        public ActionResult ModalPreOrder(string bidid, int id)
        {
            if (!User.Identity.IsAuthenticated) return Json(false);

            var user = UtilityService.GetLoginUser(_UserService, User);
            if (string.IsNullOrWhiteSpace(user.Phone)) ViewData["needphone"] = true;
            //if (string.IsNullOrWhiteSpace(user.Location)) ViewData["needlocation"] = true;
            var amount = 0;
            Provide provide = null;
            if (string.IsNullOrWhiteSpace(bidid))
            {
                provide = _ProvideService.GetById(id);
                if (provide == null) return Json(false);
                ViewData["provide"] = provide;
                amount = provide.Price;
            }
            else
            {
                var bid = _BidRequestService.GetById(Convert.ToInt32(bidid));
                //var request = _RequestService.GetById(bid.RequestID);
                //ViewData["request"] = request;
                ViewData["bid"] = bid;
                ViewData["bidid"] = bidid;
                amount = bid.PriceBid;
            }
            if (OrderHelper.IsNeedPrePayment(amount, provide))
            {
                ViewData["amount"] = OrderHelper.GetAmountPrePayment(amount, provide);
            }
            else
            {
                ViewData["amount"] = amount;
            }
            ViewData["user"] = user;
            return PartialView();
        }

        [HttpPost]
        public ActionResult CheckoutPreOrder(string bidid, int amount, int provideid, string phone)
        {
            if (!User.Identity.IsAuthenticated) return Json(false);
            var user = UtilityService.GetLoginUser(_UserService, User);
            if (!string.IsNullOrWhiteSpace(phone))
            {
                user.Phone = phone;
                _UserService.Update(user);
            }
            string urlcheckout = "";
            string url = "";
            Transaction transaction = null;
            BidRequest bid = null;
            Request request = null;
            Provide provide = null;
            User partner = null;
            if (string.IsNullOrWhiteSpace(bidid))
            {
                provide = _ProvideService.GetById(provideid);
                partner = _UserService.GetById(provide.UserID);
                if (amount == 0)
                {
                    TempData["issuccess"] = true;
                    urlcheckout = RootUrl() + "/Provide/Details/" + provide.ID;
                    //url = RootUrl() + "/Provide/Details/" + provide.ID;
                }
                else
                {

                    transaction = new Transaction()
                   {
                       Amount = amount,
                       CreatedDate = DateTime.Now,
                       ModifiedDate = DateTime.Now,
                       PayerID = user.ID,
                       ReceiverID = provide.UserID,
                       Status = (int)ETransactionStatus.Wait_Payment,
                       TransactionCode = UserUtility.GetRandomString(16),
                       TransactionType = (int)ETransactionType.Payment_PreOrder,
                       ProvideID = provideid
                   };
                    _TransactionService.Add(transaction);
                    SohaPayment pay = new SohaPayment();
                    urlcheckout = pay.BuildCheckoutUrl(RootUrl() + "/Payment/ResultPaymentPreOrder", "Đặt dịch vụ trên viecnho.com", transaction.ID.ToString(), Convert.ToInt64(amount), UserUtility.GetVerifiedEmail(user), user.Phone, user.Location ?? "");
                    //url = "/Payment/ResulstPaymentPreOrderTemp?order_code=" + transaction.ID + "&price=" + transaction.Amount;
                }

            }
            else
            {
                bid = _BidRequestService.GetById(Convert.ToInt32(bidid));
                request = _RequestService.GetById(bid.RequestID);
                partner = _UserService.GetById(bid.BidderID);
                if (amount == 0)
                {
                    TempData["issuccess"] = true;
                    TempData["bidid"] = bid.ID;
                    urlcheckout = RootUrl() + "/Request/Details/" + request.ID;
                    //url = RootUrl() + "/Request/Details/" + request.ID;
                }
                else
                {
                    transaction = new Transaction()
                   {
                       Amount = amount,
                       CreatedDate = DateTime.Now,
                       ModifiedDate = DateTime.Now,
                       PayerID = user.ID,
                       ReceiverID = bid.BidderID,
                       Status = (int)ETransactionStatus.Wait_Payment,
                       TransactionCode = UserUtility.GetRandomString(16),
                       TransactionType = (int)ETransactionType.Payment_PreOrder,
                       RequestID = request.ID
                   };
                    _TransactionService.Add(transaction);
                    SohaPayment pay = new SohaPayment();
                    urlcheckout = pay.BuildCheckoutUrl(RootUrl() + "/Payment/ResultPaymentPreOrder?bidid=" + bidid, "Đặt hàng thực hiện yêu cầu trên viecnho.com", transaction.ID.ToString(), Convert.ToInt64(amount), user.Email, user.Phone, user.Location);
                    //url = "/Payment/ResulstPaymentPreOrderTemp?bidid=" + bidid + "&order_code=" + transaction.ID + "&price=" + transaction.Amount;
                }
            }

            Order o = new Order()
            {
                ProvideID = (provide == null ? 0 : provide.ID),
                RequestID = (request == null ? 0 : request.ID),
                ModifiedDate = DateTime.Now,
                CreatedDate = DateTime.Now,
                SecretCode = SecretCodeGenerate.Generate(8),
                Status = (amount == 0 ? (int)OrderStatusV2.WaitProgress : (int)OrderStatusV2.NoActive),
                Completed = false,
                Price = (bid == null ? provide.Price : bid.PriceBid),
                Type = (int)(bid == null ? OrderType.PROVIDE : OrderType.REQUEST),
                TimeToFinish = (provide != null ? provide.TimeToComplete : 0),
                PaymentStatus = (amount == 0 ? (int)EPaymentStatus.Finish_Payment : (int)EPaymentStatus.No_Payment)
            };
            OrderHelper.SetPersonForOrder(o, user.ID, (bid == null ? provide.UserID : bid.BidderID));
            _OrderService.Add(o);
            if (transaction != null)
            {
                transaction.OrderID = o.ID;
                _TransactionService.Update(transaction);
            }
            if (amount == 0)
            {
                TempData["orderid"] = o.ID;
                if (provide != null)
                {
                    //try catch to enable and disable send email depend on resource
                    try
                    {
                        var format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailOrderProvide));
                        DictionaryOrderProvide dicorder = new DictionaryOrderProvide(UserUtility.GetVerifiedEmail(partner), user.ProperName, provide.Title, o.ID.ToString(), MessageHelper.BuildShortIDOrder(o.ID), provide.ID.ToString());
                        UserUtility.NotifyEmail(format, dicorder);

                        var notifyformat = Resources.Resource.SystemNotifyMessageOrderProvide;
                        var contentNotify = MessageHelper.BuildNotifyMessageContent(notifyformat, dicorder);

                        MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentNotify, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(o.ID)), OrderHelper.GetWorkerID(o), OrderHelper.GetPayerID(o), (int)MessageType.System_Notify, null);
                    }
                    catch (Exception) { }
                }
                else
                {
                    //try catch to enable and disable send email depend on resource
                    try
                    {
                        var format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailOrderRequest));
                        DictionaryOrderRequest dicorder = new DictionaryOrderRequest(UserUtility.GetVerifiedEmail(partner), partner.ProperName, request.Title, o.ID.ToString(), MessageHelper.BuildShortIDOrder(o.ID), request.ID.ToString());
                        UserUtility.NotifyEmail(format, dicorder);

                        var notifyformat = Resources.Resource.SystemNotifyMessageOrderRequest;
                        var contentNotify = MessageHelper.BuildNotifyMessageContent(notifyformat, dicorder);

                        MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentNotify, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(o.ID)), OrderHelper.GetWorkerID(o), OrderHelper.GetPayerID(o), (int)MessageType.System_Notify, null);

                    }
                    catch (Exception) { }
                }

                if (provide != null && provide.IsDeliveryImmediate)
                {
                    o.Status = (int)OrderStatusV2.WaitDone;
                    _OrderService.Update(o);
                    var content = Resources.Resource.SystemMessageAcceptOrder;
                    var info = new MMessageEmbedInfo()
                      {
                          Type = (int)EEmbedInfoType.Accept
                      };
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDOrder(o.ID), OrderHelper.GetPayerID(o), OrderHelper.GetWorkerID(o), (provide != null ? (int)MessageType.ORDER_PROVIDE : (int)MessageType.ORDER_REQUEST), info);
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(o.ID)), OrderHelper.GetPayerID(o), OrderHelper.GetWorkerID(o), (int)MessageType.System_Notify, info);


                    content = Resources.Resource.SystemMessageDeliveryOrder;
                    info = new MMessageEmbedInfo()
                    {
                        Type = (int)EEmbedInfoType.Delivery,
                        AllowDownload = true,
                        Download = UploadHelper.GetLinkDownload(OrderHelper.GetWorkerID(o), provide.Download, OrderHelper.GetPayerID(o), o.ID)
                    };
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDOrder(o.ID), OrderHelper.GetPayerID(o), OrderHelper.GetWorkerID(o), (provide != null ? (int)MessageType.ORDER_PROVIDE : (int)MessageType.ORDER_REQUEST), info);
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(o.ID)), OrderHelper.GetPayerID(o), OrderHelper.GetWorkerID(o), (int)MessageType.System_Notify, info);

                    //send notify for provide owner

                    var notifyformat = Resources.Resource.SystemNotifyMessageAutoDeliveryForWorker;
                    var factory = new EmailFactory();
                    factory.GetDictionary().Add("provide", provide.Title);
                    factory.GetDictionary().Add("client", user.ProperName);
                    var notifycontent = factory.ReplaceWithDictionary(notifyformat);
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, notifycontent, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(o.ID)), OrderHelper.GetWorkerID(o), (int)EUserID.SystemUser, (int)MessageType.System_Notify, null);
                }

                if (partner != null && partner.Premium && partner.Phone != null)
                {
                    SmsHelpers smsHelper = new SmsHelpers();
                    string messid = "sms_" + o.ID + "_" + "OrderSms";
                    string smsresult = "";
                    string smsContent = Resources.Resource.SmsOrderContent.Replace("{buyer}", StringHanding.Convert(user.ProperName)).Replace("{title}", StringHanding.Convert((provide != null ? provide.Title : request.Title)));
                    var smsResultObj = smsHelper.Send(messid, partner.Phone, smsContent, out smsresult);
                    LogHelper.SmsLog(_SmsLogService, smsResultObj, smsresult, partner.ID, o.ID, smsContent);
                }
            }
            MessageHelper.NewConversation(_MConversationService, null, o, provide, request, user, partner, MessageHelper.BuildShortIDOrder(o.ID), (int)(provide != null ? MessageType.ORDER_PROVIDE : MessageType.ORDER_REQUEST));


            return Redirect(urlcheckout);
            //return Redirect(url);
        }

        public ActionResult ResultPaymentPreOrder()
        {
            //var premiumcode = Request["order_code"];
            var transactionid = Convert.ToInt32(Request["order_code"]);
            var transaction = _TransactionService.GetById(transactionid);

            User payer = _UserService.GetById(transaction.PayerID);
            User worker = _UserService.GetById(transaction.ReceiverID);
            var bidid = Request["bidid"];
            var controller = "";
            var paraid = 0;
            BidRequest bid = null;
            Provide provide = null;
            Request request = null;
            Order order = null;
            order = _OrderService.GetById(transaction.OrderID);
            if (bidid == null)
            {
                controller = "Provide";
                paraid = transaction.ProvideID;
                provide = _ProvideService.GetById(paraid);
                transaction.Provide = provide;
            }
            else
            {
                controller = "Request";
                paraid = transaction.RequestID;
                //kiem tra dam bao bidid dung
                bid = _BidRequestService.GetById(Convert.ToInt32(bidid));
                if (OrderHelper.GetAmountPrePayment(bid.PriceBid, provide) != transaction.Amount || bid.BidderID != transaction.ReceiverID)
                {
                    return RedirectToAction("Details", controller, new { id = paraid });
                }
                request = _RequestService.GetById(paraid);
                transaction.Request = request;
            }

            var price = Convert.ToInt32(Request["price"]);
            if (transaction == null)
            {
                var errortext = "Không tìm thấy giao dịch.";
                TempData["orderid"] = order.ID;
                TempData["result"] = errortext;
                TempData["issuccess"] = false;
                SendEmailFailedPayment(false, payer, price.ToString(), errortext, (transaction.Provide == null ? transaction.Request.Title : transaction.Provide.Title), paraid.ToString());
                return RedirectToAction("Details", controller, new { id = paraid });
            }
            string error_text = !string.IsNullOrEmpty(Request["error_text"]) ? Request["error_text"] : "";
            SohaPayment pay = new SohaPayment();
            bool check = pay.VerifyReturnUrl();
            string html = "";
            if (check && error_text == "")
            {
                var stt = transaction.Status;
                if (stt == (int)ETransactionStatus.Wait_Payment)
                {
                    transaction.Status = (int)ETransactionStatus.Payer_Payment_Success;
                    transaction.ModifiedDate = DateTime.Now;
                    transaction.Provide = null;
                    transaction.Request = null;
                    _TransactionService.Update(transaction);

                    if (OrderHelper.IsNeedPrePayment(order.Price, provide))
                    {
                        order.PaymentStatus = (int)EPaymentStatus.Pre_Payment;
                    }
                    else
                    {
                        order.PaymentStatus = (int)EPaymentStatus.Finish_Payment;
                    }
                    order.Status = (int)OrderStatusV2.WaitProgress;
                    _OrderService.Update(order);
                    if (bid == null)
                    {
                        //try catch to enable and disable send email depend on resource
                        try
                        {
                            var format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailOrderProvide));
                            DictionaryOrderProvide dicorder = new DictionaryOrderProvide(UserUtility.GetVerifiedEmail(worker), payer.ProperName, provide.Title, order.ID.ToString(), MessageHelper.BuildShortIDOrder(order.ID), provide.ID.ToString());
                            UserUtility.NotifyEmail(format, dicorder);


                            var notifyformat = Resources.Resource.SystemNotifyMessageOrderProvide;
                            var contentNotify = MessageHelper.BuildNotifyMessageContent(notifyformat, dicorder);

                            MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentNotify, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetWorkerID(order), OrderHelper.GetPayerID(order), (int)MessageType.System_Notify, null);
                        }
                        catch (Exception) { }
                    }
                    else
                    {
                        //try catch to enable and disable send email depend on resource
                        try
                        {
                            var format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailOrderRequest));
                            DictionaryOrderRequest dicorder = new DictionaryOrderRequest(UserUtility.GetVerifiedEmail(worker), payer.ProperName, request.Title, order.ID.ToString(), MessageHelper.BuildShortIDOrder(order.ID), request.ID.ToString());
                            UserUtility.NotifyEmail(format, dicorder);

                            var notifyformat = Resources.Resource.SystemNotifyMessageOrderRequest;
                            var contentNotify = MessageHelper.BuildNotifyMessageContent(notifyformat, dicorder);

                            MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentNotify, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetWorkerID(order), OrderHelper.GetPayerID(order), (int)MessageType.System_Notify, null);

                        }
                        catch (Exception) { }
                        bid.IsSuccess = true;
                        _BidRequestService.Update(bid);
                    }
                    var content = Resources.Resource.SystemMessageOrder.Replace("{price}", (OrderHelper.GetAmountPrePayment(order.Price, provide)).ToString());
                    var info = new MMessageEmbedInfo()
                    {
                        Type = (int)EEmbedInfoType.Payment
                    };
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDOrder(order.ID), OrderHelper.GetWorkerID(order), OrderHelper.GetPayerID(order), (provide != null ? (int)MessageType.ORDER_PROVIDE : (int)MessageType.ORDER_REQUEST), info);
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetWorkerID(order), OrderHelper.GetPayerID(order), (int)MessageType.System_Notify, info);

                    if (provide != null && provide.IsDeliveryImmediate)
                    {
                        order.Status = (int)OrderStatusV2.WaitDone;
                        _OrderService.Update(order);
                        content = Resources.Resource.SystemMessageAcceptOrder;
                        info = new MMessageEmbedInfo()
                        {
                            Type = (int)EEmbedInfoType.Accept
                        };
                        MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDOrder(order.ID), OrderHelper.GetPayerID(order), OrderHelper.GetWorkerID(order), (provide != null ? (int)MessageType.ORDER_PROVIDE : (int)MessageType.ORDER_REQUEST), info);
                        MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetPayerID(order), OrderHelper.GetWorkerID(order), (int)MessageType.System_Notify, info);


                        content = Resources.Resource.SystemMessageDeliveryOrder;
                        info = new MMessageEmbedInfo()
                        {
                            Type = (int)EEmbedInfoType.Delivery,
                            AllowDownload = true,
                            Download = UploadHelper.GetLinkDownload(OrderHelper.GetWorkerID(order), provide.Download, OrderHelper.GetPayerID(order), order.ID)
                        };
                        MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDOrder(order.ID), OrderHelper.GetPayerID(order), OrderHelper.GetWorkerID(order), (provide != null ? (int)MessageType.ORDER_PROVIDE : (int)MessageType.ORDER_REQUEST), info);
                        MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetPayerID(order), OrderHelper.GetWorkerID(order), (int)MessageType.System_Notify, info);

                        //send notify for provide owner

                        var notifyformat = Resources.Resource.SystemNotifyMessageAutoDeliveryForWorker;
                        var factory = new EmailFactory();
                        factory.GetDictionary().Add("provide", provide.Title);
                        factory.GetDictionary().Add("client", payer.ProperName);
                        var notifycontent = factory.ReplaceWithDictionary(notifyformat);
                        MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, notifycontent, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetWorkerID(order), (int)EUserID.SystemUser, (int)MessageType.System_Notify, null);
                    }

                    if (worker != null && worker.Premium && worker.Phone != null)
                    {
                        SmsHelpers smsHelper = new SmsHelpers();
                        string messid = "sms_" + order.ID + "_" + "OrderSms";
                        string smsresult = "";
                        string smsContent = Resources.Resource.SmsOrderContent.Replace("{buyer}", StringHanding.Convert(payer.ProperName)).Replace("{title}", StringHanding.Convert(provide.Title));
                        var smsResultObj = smsHelper.Send(messid, worker.Phone, smsContent, out smsresult);
                        LogHelper.SmsLog(_SmsLogService, smsResultObj, smsresult, worker.ID, order.ID, smsContent);
                    }

                    if (payer != null && payer.Phone != null)
                    {
                        SmsHelpers smsHelper = new SmsHelpers();
                        string messid = "";
                        string smsresult = "";
                        string smsContent = "";
                        if (controller == "Provide")
                        {
                            string title = StringHanding.Convert(provide.Title);
                            messid = "sms_" + provide.ID + "_" + "SohapayProvideSms";
                            smsContent = Resources.Resource.SohaPayProvide.Replace("{title}", title).Replace("{price}", transaction.Amount.ToString());
                        }
                        else
                        {
                            messid = "sms_" + request.ID + "_" + "SohapayRequestSms";
                            string title = StringHanding.Convert(request.Title);
                            smsContent = Resources.Resource.SohaPayRequest.Replace("{title}", title).Replace("{price}", transaction.Amount.ToString());
                        }
                        var smsResultObj = smsHelper.Send(messid, payer.Phone, smsContent, out smsresult);
                        LogHelper.SmsLog(_SmsLogService, smsResultObj, smsresult, payer.ID, 0, smsContent);
                    }
                    var bidder = _UserService.GetById(transaction.ReceiverID);
                    //send notify
                    //try catch to enable and disable send email depend on resource
                    try
                    {
                        var format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailOrderStep1Sucess));
                        var email = UserUtility.GetVerifiedEmail(payer);
                        DictionaryTransactionOrderStep1Success dic = new DictionaryTransactionOrderStep1Success(email, payer.ProperName, price.ToString(), (transaction.Provide == null ? transaction.Request.Title : transaction.Provide.Title), paraid.ToString());
                        UserUtility.NotifyEmail(format, dic);

                        var notifyformat = Resources.Resource.SystemNotifyMessageTransactionOrderStep1Success;
                        var contentnotify = MessageHelper.BuildNotifyMessageContent(notifyformat, dic);
                        MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentnotify, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), payer.ID, (int)EUserID.SystemUser, (int)MessageType.System_Notify, null);
                        ////send to bidder
                        //email = UserUtility.GetVerifiedEmail(bidder);
                        //dic = new DictionaryTransactionOrderStep1Success(email, uSms.ProperName, price.ToString(),(transaction.Provide==null?transaction.Request.Title:transaction.Provide.Title),paraid.ToString());
                        //UserUtility.NotifyEmail(format, dic);
                    }
                    catch (Exception) { }
                }
                html += "Cám ơn quý khách, quá trình thanh toán đã được hoàn tất. ";
                TempData["bidid"] = bidid;
                TempData["issuccess"] = true;
            }
            else if (check)
            {
                html += "Quá trình thanh toán không thành công do lỗi: " + error_text;
                TempData["issuccess"] = false;
            }
            else
            {
                html += "Thông tin bảo mật không đúng";
                TempData["issuccess"] = false;
            }

            TempData["orderid"] = order.ID;
            TempData["result"] = html;
            if (!Convert.ToBoolean(ViewData["issuccess"]))
            {
                SendEmailFailedPayment(false, payer, price.ToString(), html, (provide == null ? request.Title : provide.Title), paraid.ToString());
            }
            return RedirectToAction("Details", controller, new { id = paraid });
        }

        private void SendEmailFailedPayment(bool ispremium, User user, string amount, string errortext, string provide, string provideid)
        {
            //send notify
            //try catch to enable and disable send email depend on resource
            try
            {
                var email = UserUtility.GetVerifiedEmail(user);
                DictionaryTransactionFailed dic = null;
                EmailFormat format = null;

                if (ispremium)
                {
                    format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailPremiumFailed));
                    dic = new DictionaryTransactionPremiumFailed(email, user.ProperName, amount, errortext);
                }
                else
                {
                    format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailOrderStep1Failed));
                    dic = new DictionaryTransactionOrderStep1Failed(email, user.ProperName, amount, errortext, provide, provideid);
                }

                UserUtility.NotifyEmail(format, dic);
            }
            catch (Exception) { }
        }

        [HttpPost]
        public ActionResult ModalPaymentOrder(int id)
        {
            if (!User.Identity.IsAuthenticated) return Json(false);

            var user = UtilityService.GetLoginUser(_UserService, User);
            if (string.IsNullOrWhiteSpace(user.Phone)) ViewData["needphone"] = true;
            //if (string.IsNullOrWhiteSpace(user.Location)) ViewData["needlocation"] = true;
            var amount = 0;
            var order = _OrderService.GetById(id);

            if (order == null) return Json(false);
            amount = order.Price - OrderHelper.GetAmountPrePayment(order.Price, null);
            ViewData["amount"] = amount;
            ViewData["paymenttitle"] = (order.Type == (int)OrderType.PROVIDE ? _ProvideService.GetById(order.ProvideID).Title : _RequestService.GetById(order.RequestID).Title);
            ViewData["user"] = user;
            ViewData["order"] = order;
            return PartialView();
        }

        [HttpPost]
        public ActionResult CheckoutPaymentOrder(int orderid, int amount, string phone)
        {
            if (!User.Identity.IsAuthenticated) return Json(false);
            var user = UtilityService.GetLoginUser(_UserService, User);
            if (!string.IsNullOrWhiteSpace(phone))
            {
                user.Phone = phone;
                _UserService.Update(user);
            }
            string urlcheckout = "";
            var order = _OrderService.GetById(orderid);
            var transaction = new Transaction()
            {
                Amount = amount,
                CreatedDate = DateTime.Now,
                ModifiedDate = DateTime.Now,
                PayerID = user.ID,
                ReceiverID = OrderHelper.GetWorkerID(order),
                Status = (int)ETransactionStatus.Wait_Payment,
                TransactionCode = UserUtility.GetRandomString(16),
                TransactionType = (int)ETransactionType.Payment_Order,
                OrderID = orderid
            };
            _TransactionService.Add(transaction);
            SohaPayment pay = new SohaPayment();
            urlcheckout = pay.BuildCheckoutUrl(RootUrl() + "/Payment/ResultPaymentOrder", "Thanh toán đơn hàng trên viecnho.com", transaction.ID.ToString(), Convert.ToInt64(amount), user.Email, user.Phone, user.Location ?? "");

            return Redirect(urlcheckout);
        }

        public ActionResult ResultPaymentOrder()
        {
            //var premiumcode = Request["order_code"];
            var transactionid = Convert.ToInt32(Request["order_code"]);
            var transaction = _TransactionService.GetById(transactionid);
            User payer = _UserService.GetById(transaction.PayerID);
            User worker = _UserService.GetById(transaction.ReceiverID);
            var paraid = transaction.OrderID;
            var order = _OrderService.GetById(paraid);
            Provide provide = null;
            Request request = null;
            BidRequest bid = null;
            if (order.Type == (int)OrderType.PROVIDE)
            {
                transaction.Provide = _ProvideService.GetById(order.ProvideID);
                provide = transaction.Provide;
            }
            else
            {
                transaction.Request = _RequestService.GetById(order.RequestID);
                request = transaction.Request;
            }
            var price = Convert.ToInt32(Request["price"]);
            if (transaction == null)
            {
                var errortext = "Không tìm thấy giao dịch.";
                TempData["result"] = errortext;
                TempData["issuccess"] = false;
                SendEmailFailedPayment(false, payer, price.ToString(), errortext, (transaction.Provide == null ? transaction.Request.Title : transaction.Provide.Title), paraid.ToString());
                return RedirectToAction("Details", "Order", new { id = paraid });
            }
            string error_text = !string.IsNullOrEmpty(Request["error_text"]) ? Request["error_text"] : "";
            SohaPayment pay = new SohaPayment();
            bool check = pay.VerifyReturnUrl();
            string html = "";
            if (check && error_text == "")
            {
                var stt = transaction.Status;
                if (stt == (int)ETransactionStatus.Wait_Payment)
                {
                    transaction.Status = (int)ETransactionStatus.Payer_Payment_Success;
                    transaction.ModifiedDate = DateTime.Now;
                    transaction.Provide = null;
                    transaction.Request = null;
                    _TransactionService.Update(transaction);

                    order.PaymentStatus = (int)EPaymentStatus.Finish_Payment;
                    _OrderService.Update(order);

                    var content = Resources.Resource.SystemMessageOrder.Replace("{price}", (order.Price - OrderHelper.GetAmountPrePayment(order.Price, provide)).ToString());
                    var info = new MMessageEmbedInfo()
                    {
                        Type = (int)EEmbedInfoType.Payment
                    };
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDOrder(order.ID), OrderHelper.GetWorkerID(order), OrderHelper.GetPayerID(order), (provide != null ? (int)MessageType.ORDER_PROVIDE : (int)MessageType.ORDER_REQUEST), info);
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetWorkerID(order), OrderHelper.GetPayerID(order), (int)MessageType.System_Notify, info);

                    if (payer != null && payer.Phone != null)
                    {
                        SmsHelpers smsHelper = new SmsHelpers();
                        string messid = "";
                        string smsresult = "";
                        string smsContent = "";
                        if (order.Type == (int)OrderType.PROVIDE)
                        {
                            transaction.Provide = _ProvideService.GetById(order.ProvideID);
                            var p = transaction.Provide;
                            string title = StringHanding.Convert(p.Title);
                            messid = "sms_" + p.ID + "_" + "SohapayProvideSms";
                            smsContent = Resources.Resource.SohaPayProvide.Replace("{title}", title).Replace("{price}", transaction.Amount.ToString());
                        }
                        else
                        {
                            transaction.Request = _RequestService.GetById(order.RequestID);
                            var r = transaction.Request;
                            messid = "sms_" + r.ID + "_" + "SohapayRequestSms";
                            string title = StringHanding.Convert(r.Title);
                            smsContent = Resources.Resource.SohaPayRequest.Replace("{title}", title).Replace("{price}", transaction.Amount.ToString());
                        }
                        var smsResultObj = smsHelper.Send(messid, payer.Phone, smsContent, out smsresult);
                        _SmsLogService.Add(new SmsLog()
                        {
                            DateCreated = DateTime.Now,
                            MessageID = smsResultObj.message_id,
                            SmsResult = smsresult,
                            Status = smsResultObj.status,
                            UserID = payer.ID,
                            SmsContent = smsContent
                        });
                    }
                    _MMessageService.AllowDownload(MessageHelper.BuildShortIDOrder(order.ID));
                    var bidder = _UserService.GetById(transaction.ReceiverID);
                    //send notify
                    //try catch to enable and disable send email depend on resource
                    try
                    {
                        var format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailOrderStep1Sucess));
                        var email = UserUtility.GetVerifiedEmail(payer);
                        DictionaryTransactionOrderStep1Success dic = new DictionaryTransactionOrderStep1Success(email, payer.ProperName, price.ToString(), (transaction.Provide == null ? transaction.Request.Title : transaction.Provide.Title), paraid.ToString());
                        UserUtility.NotifyEmail(format, dic);

                        var notifyformat = Resources.Resource.SystemNotifyMessageTransactionOrderStep1Success;
                        var contentnotify = MessageHelper.BuildNotifyMessageContent(notifyformat, dic);
                        MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentnotify, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), payer.ID, (int)EUserID.SystemUser, (int)MessageType.System_Notify, null);
                        //send to bidder
                        //email = UserUtility.GetVerifiedEmail(bidder);
                        //dic = new DictionaryTransactionOrderStep1Success(email, uSms.ProperName, price.ToString(),(transaction.Provide==null?transaction.Request.Title:transaction.Provide.Title),paraid.ToString());
                        //UserUtility.NotifyEmail(format, dic);
                    }
                    catch (Exception) { }
                }
                html += "Cám ơn quý khách, quá trình thanh toán đã được hoàn tất. ";
                TempData["issuccess"] = true;
            }
            else if (check)
            {
                html += "Quá trình thanh toán không thành công do lỗi: " + error_text;
                TempData["issuccess"] = false;
            }
            else
            {
                html += "Thông tin bảo mật không đúng";
                TempData["issuccess"] = false;
            }
            TempData["result"] = html;
            if (!Convert.ToBoolean(ViewData["issuccess"]))
            {
                SendEmailFailedPayment(false, payer, price.ToString(), html, (transaction.Provide == null ? transaction.Request.Title : transaction.Provide.Title), paraid.ToString());
            }
            return RedirectToAction("Details", "Order", new { id = paraid });
        }

        public ActionResult ResulstPaymentPreOrderTemp()
        {
            var transactionid = Convert.ToInt32(Request["order_code"]);
            var transaction = _TransactionService.GetById(transactionid);

            User payer = _UserService.GetById(transaction.PayerID);
            User worker = _UserService.GetById(transaction.ReceiverID);
            var bidid = Request["bidid"];
            var controller = "";
            var paraid = 0;
            BidRequest bid = null;
            Provide provide = null;
            Request request = null;
            Order order = null;
            order = _OrderService.GetById(transaction.OrderID);
            if (bidid == null)
            {
                controller = "Provide";
                paraid = transaction.ProvideID;
                provide = _ProvideService.GetById(paraid);
                transaction.Provide = provide;
            }
            else
            {
                controller = "Request";
                paraid = transaction.RequestID;
                //kiem tra dam bao bidid dung
                bid = _BidRequestService.GetById(Convert.ToInt32(bidid));
                if (OrderHelper.GetAmountPrePayment(bid.PriceBid, provide) != transaction.Amount || bid.BidderID != transaction.ReceiverID)
                {
                    return RedirectToAction("Details", controller, new { id = paraid });
                }
                request = _RequestService.GetById(paraid);
                transaction.Request = request;
            }

            var price = Convert.ToInt32(Request["price"]);
            if (transaction == null)
            {
                var errortext = "Không tìm thấy giao dịch.";
                TempData["orderid"] = order.ID;
                TempData["result"] = errortext;
                TempData["issuccess"] = false;
                SendEmailFailedPayment(false, payer, price.ToString(), errortext, (transaction.Provide == null ? transaction.Request.Title : transaction.Provide.Title), paraid.ToString());
                return RedirectToAction("Details", controller, new { id = paraid });
            }
            var stt = transaction.Status;
            if (stt == (int)ETransactionStatus.Wait_Payment)
            {
                transaction.Status = (int)ETransactionStatus.Payer_Payment_Success;
                transaction.ModifiedDate = DateTime.Now;
                transaction.Provide = null;
                transaction.Request = null;
                _TransactionService.Update(transaction);

                if (OrderHelper.IsNeedPrePayment(order.Price, provide))
                {
                    order.PaymentStatus = (int)EPaymentStatus.Pre_Payment;
                }
                else
                {
                    order.PaymentStatus = (int)EPaymentStatus.Finish_Payment;
                }
                order.Status = (int)OrderStatusV2.WaitProgress;
                _OrderService.Update(order);
                if (bid == null)
                {
                    //try catch to enable and disable send email depend on resource
                    try
                    {
                        var format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailOrderProvide));
                        DictionaryOrderProvide dicorder = new DictionaryOrderProvide(UserUtility.GetVerifiedEmail(worker), payer.ProperName, provide.Title, order.ID.ToString(), MessageHelper.BuildShortIDOrder(order.ID), provide.ID.ToString());
                        UserUtility.NotifyEmail(format, dicorder);


                        var notifyformat = Resources.Resource.SystemNotifyMessageOrderProvide;
                        var contentNotify = MessageHelper.BuildNotifyMessageContent(notifyformat, dicorder);

                        MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentNotify, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetWorkerID(order), OrderHelper.GetPayerID(order), (int)MessageType.System_Notify, null);
                    }
                    catch (Exception) { }
                }
                else
                {
                    //try catch to enable and disable send email depend on resource
                    try
                    {
                        var format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailOrderRequest));
                        DictionaryOrderRequest dicorder = new DictionaryOrderRequest(UserUtility.GetVerifiedEmail(worker), payer.ProperName, request.Title, order.ID.ToString(), MessageHelper.BuildShortIDOrder(order.ID), request.ID.ToString());
                        UserUtility.NotifyEmail(format, dicorder);

                        var notifyformat = Resources.Resource.SystemNotifyMessageOrderRequest;
                        var contentNotify = MessageHelper.BuildNotifyMessageContent(notifyformat, dicorder);

                        MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentNotify, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetWorkerID(order), OrderHelper.GetPayerID(order), (int)MessageType.System_Notify, null);

                    }
                    catch (Exception) { }
                    bid.IsSuccess = true;
                    _BidRequestService.Update(bid);
                }
                var content = Resources.Resource.SystemMessageOrder.Replace("{price}", (OrderHelper.GetAmountPrePayment(order.Price, provide)).ToString());
                var info = new MMessageEmbedInfo()
                {
                    Type = (int)EEmbedInfoType.Payment
                };
                MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDOrder(order.ID), OrderHelper.GetWorkerID(order), OrderHelper.GetPayerID(order), (provide != null ? (int)MessageType.ORDER_PROVIDE : (int)MessageType.ORDER_REQUEST), info);
                MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetWorkerID(order), OrderHelper.GetPayerID(order), (int)MessageType.System_Notify, info);

                if (provide != null && provide.IsDeliveryImmediate)
                {
                    order.Status = (int)OrderStatusV2.WaitDone;
                    _OrderService.Update(order);
                    content = Resources.Resource.SystemMessageAcceptOrder;
                    info = new MMessageEmbedInfo()
                    {
                        Type = (int)EEmbedInfoType.Accept
                    };
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDOrder(order.ID), OrderHelper.GetPayerID(order), OrderHelper.GetWorkerID(order), (provide != null ? (int)MessageType.ORDER_PROVIDE : (int)MessageType.ORDER_REQUEST), info);
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetPayerID(order), OrderHelper.GetWorkerID(order), (int)MessageType.System_Notify, info);


                    content = Resources.Resource.SystemMessageDeliveryOrder;
                    info = new MMessageEmbedInfo()
                    {
                        Type = (int)EEmbedInfoType.Delivery,
                        AllowDownload = true,
                        Download = UploadHelper.GetLinkDownload(OrderHelper.GetWorkerID(order), provide.Download, OrderHelper.GetPayerID(order), order.ID)
                    };
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDOrder(order.ID), OrderHelper.GetPayerID(order), OrderHelper.GetWorkerID(order), (provide != null ? (int)MessageType.ORDER_PROVIDE : (int)MessageType.ORDER_REQUEST), info);
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetPayerID(order), OrderHelper.GetWorkerID(order), (int)MessageType.System_Notify, info);

                    //send notify for provide owner

                    var notifyformat = Resources.Resource.SystemNotifyMessageAutoDeliveryForWorker;
                    var factory = new EmailFactory();
                    factory.GetDictionary().Add("provide", provide.Title);
                    factory.GetDictionary().Add("client", payer.ProperName);
                    var notifycontent = factory.ReplaceWithDictionary(notifyformat);
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, notifycontent, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetWorkerID(order), (int)EUserID.SystemUser, (int)MessageType.System_Notify, null);
                }

                if (worker != null && worker.Premium && worker.Phone != null)
                {
                    SmsHelpers smsHelper = new SmsHelpers();
                    string messid = "sms_" + order.ID + "_" + "OrderSms";
                    string smsresult = "";
                    string smsContent = Resources.Resource.SmsOrderContent.Replace("{buyer}", StringHanding.Convert(payer.ProperName)).Replace("{title}", StringHanding.Convert(provide.Title));
                    var smsResultObj = smsHelper.Send(messid, worker.Phone, smsContent, out smsresult);
                    LogHelper.SmsLog(_SmsLogService, smsResultObj, smsresult, worker.ID, order.ID, smsContent);
                }

                if (payer != null && payer.Phone != null)
                {
                    SmsHelpers smsHelper = new SmsHelpers();
                    string messid = "";
                    string smsresult = "";
                    string smsContent = "";
                    if (controller == "Provide")
                    {
                        string title = StringHanding.Convert(provide.Title);
                        messid = "sms_" + provide.ID + "_" + "SohapayProvideSms";
                        smsContent = Resources.Resource.SohaPayProvide.Replace("{title}", title).Replace("{price}", transaction.Amount.ToString());
                    }
                    else
                    {
                        messid = "sms_" + request.ID + "_" + "SohapayRequestSms";
                        string title = StringHanding.Convert(request.Title);
                        smsContent = Resources.Resource.SohaPayRequest.Replace("{title}", title).Replace("{price}", transaction.Amount.ToString());
                    }
                    var smsResultObj = smsHelper.Send(messid, payer.Phone, smsContent, out smsresult);
                    LogHelper.SmsLog(_SmsLogService, smsResultObj, smsresult, payer.ID, 0, smsContent);
                }
                var bidder = _UserService.GetById(transaction.ReceiverID);
                //send notify
                //try catch to enable and disable send email depend on resource
                try
                {
                    var format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailOrderStep1Sucess));
                    var email = UserUtility.GetVerifiedEmail(payer);
                    DictionaryTransactionOrderStep1Success dic = new DictionaryTransactionOrderStep1Success(email, payer.ProperName, price.ToString(), (transaction.Provide == null ? transaction.Request.Title : transaction.Provide.Title), paraid.ToString());
                    UserUtility.NotifyEmail(format, dic);

                    var notifyformat = Resources.Resource.SystemNotifyMessageTransactionOrderStep1Success;
                    var contentnotify = MessageHelper.BuildNotifyMessageContent(notifyformat, dic);
                    MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentnotify, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), payer.ID, (int)EUserID.SystemUser, (int)MessageType.System_Notify, null);
                    ////send to bidder
                    //email = UserUtility.GetVerifiedEmail(bidder);
                    //dic = new DictionaryTransactionOrderStep1Success(email, uSms.ProperName, price.ToString(),(transaction.Provide==null?transaction.Request.Title:transaction.Provide.Title),paraid.ToString());
                    //UserUtility.NotifyEmail(format, dic);
                }
                catch (Exception) { }
            }
            var html = "Cám ơn quý khách, quá trình thanh toán đã được hoàn tất. ";
            TempData["bidid"] = bidid;
            TempData["issuccess"] = true;

            TempData["orderid"] = order.ID;
            TempData["result"] = html;
            if (!Convert.ToBoolean(ViewData["issuccess"]))
            {
                SendEmailFailedPayment(false, payer, price.ToString(), html, (provide == null ? request.Title : provide.Title), paraid.ToString());
            }
            return RedirectToAction("Details", controller, new { id = paraid });
        }
    }
}